<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/15
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller;

use ImiApp\ApiServer\Api\Controller\Tpmecms;
use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
// use ImiApp\ApiServer\Common\AuthApi;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Config;
use ImiApp\ApiServer\Api\Model\FaUser as User;
use PSpell\Config as PSpellConfig;

// use ImiApp\ApiServer\Common\Auth\AuthManager;


//用户公共接口

/**
 * 
 * @Auth(name="token",nologin={"get_index_app","get_user_data"},name="token")
 * @Controller("/user_com/")
 */
class UserCom extends Tpmecms
{

    // protected $noNeedLogin = ['get_index_app', 'get_user_data'];
    // protected $noNeedRight = ['*'];




    /**
     * 修改用户的昵称和头像等资料
     *
     * @param string $nickname 昵称
     * @param string $head_img 头像
     * @param int $sex 性别:0=未知,1=男,2=女
     * @param string $birthday 生日
     * @param int $area_id 地区id
     * @return void
     * @Action
     */
    public function update_me_info($nickname, $head_img, $sex = null, $birthday = null, $area_id = null)
    {
        $u['id'] = $this->auth->id();
        $data['nickname'] = $nickname;
        $data['avatar'] = $head_img;
        if ($sex)
            $data['sex'] = $sex;
        if ($birthday)
            $data['birthday'] = $birthday;
        if ($area_id)
            $data['area_id'] = $area_id;

        $res = Db::name('user')->whereEx($u)->update($data);
        if ($res) {
            return $this->success('修改成功');
        }
        return $this->success('没修改');
    }



    /**
     * 修改用户资料
     *
     * @param string $nickname 昵称
     * @param string $avatar 头像
     * @param int $sex 性别:0=未知,1=男,2=女
     * @param string $birthday 生日
     * @param string $bio 签名个言
     * @param int $area_id 地区id
     * @param string $wechat_openid 微信openid
     * @param string $wechat_name 微信真实姓名
     * @param string $skill 技能
     * @return void
     * @Action
     */
    public function update_user(?string $nickname = null, ?string $avatar = null, ?int $sex = null, ?string $birthday = null, ?int $area_id = null, ?string $wechat_openid = null, ?string $wechat_name = null, ?string $bio = null, ?string $skill = null)
    {

        $u['id'] = $this->auth->user()->id;
        $data = null;
        if ($nickname)
            $data['nickname'] = $nickname;
        if ($avatar)
            $data['avatar'] = $avatar;
        if ($sex)
            $data['sex'] = (string)$sex;

        if ($birthday)
            $data['birthday'] = $birthday;
        if ($bio)
            $data['bio'] = $bio;

        if ($area_id)
            $data['area_id'] = $area_id;

        if ($skill)
            $data['skill'] = $skill;

        if ($wechat_openid && empty($this->auth->user()->wechat_openid))
            $data['wechat_openid'] = $wechat_openid;
        if ($wechat_name && empty($this->auth->user()->wechat_openid))
            $data['wechat_name'] = $wechat_name;

        if (!$data) {
            return $this->error('没有可以修改的信息');
        }
        var_dump($data);
        $res = Db::name('user')->whereEx($u)->update($data);
        if ($res) {
            return $this->success('修改成功');
        }
        return $this->success('没修改');
    }


    /**
     * 用户实名认证
     *
     * @param string $name 姓名
     * @param string $mobile 手机号
     * @param string $sfz 身份证号码
     * @param int $sfz1 身份证正面
     * @param string $sfz2 身份证反面
     * @param string $sfz3 人像照片
     * @param int $address 联系住址
     * @param string $skill 技能介绍
     * @param int $area_id 地区id
     * @return void
     * @Action
     */
    public function update_realname($name, $sfz, $sfz1 = null, $sfz2 = null, $sfz3 = null, $address = null, $mobile = null, $skill = null, $area_id = null)
    {
        $u['id'] = $this->auth->id();

        if ($area_id) {
            $area = $this->GetAreaAllData($area_id);
            unset($area['area_id']);
            $data = $area;
        }

        $price = (float) config('realname_price');
        if ($this->auth->money() < $price) {
            return $this->error('余额不足', $price, CODE_余额不足);
        }

        $data['name'] = $name;
        $data['sfz'] = $sfz;
        if (!$this->check_sfz_card($sfz))
            return $this->error('身份证号错误', $sfz, CODE_身份证号错误);

        if ($sfz1)
            $data['sfz1_image'] = $sfz1;
        if ($sfz2)
            $data['sfz2_image'] = $sfz2;
        if ($sfz3)
            $data['sfz3_image'] = $sfz3;
        if ($skill)
            $data['skill'] = $skill;

        if ($address)
            $data['address'] = $address;
        // if (!\think\Validate::regex($mobile, "^1\d{10}$")) {
        //     return $this->error('手机号错误', $mobile, CODE_手机号错误);
        // }
        $user = User::find(['mobile' => $mobile]);
        // $user = \app\common\model\User::getByMobile($mobile);
        if ($user && $user->id != $this->auth->id()) {
            return $this->error('该手机号已有用户存在', null, CODE_手机号已有用户存在);
        }



        if ($mobile)
            $data['mobile'] = $mobile;

        if (config('realname_switch')) {
            if ($this->VerifyRealNameApi($data))
                $data['real_status'] = '1';
            $this->DecUserMoney($this->auth->user()->id, $price, '实名认证费用', 9, 0);
        } else {
            $data['real_status'] = '1';
        }
        // 验证用户实名信息



        $res = Db::name('user')->whereEx($u)->update($data);
        if ($res) {
            return $this->success('修改成功');
        }
        return $this->success('没修改');
    }





    /**
     * 获取用户信息
     *
     * @return void
     * @Action
     */
    public function get_user()
    {
        $user = Db::name('user')->where('id', '=', $this->auth->id())->select()->get();
        $list['user'] = $this->ChageSelfUserData($user);
        $list['strore'] = Db::name('store')->where('user_id', '=', $this->auth->id())->select()->get();

        $after = $this->getAfterData($user);
        $list['after'] = $after;
        return $this->success($this->auth->id(), $list);
    }

    /**
     * 获取用户信息
     *
     * @return void
     * @Action
     */
    public function get_user2()
    {
        $user = Db::name('user')->where('id', '=', $this->auth->id())->select()->get();
        $list['user'] = $this->ChageSelfUserData($user);
        // $list['strore'] = Db::name('store')->where('user_id', '=', $this->auth->id())->select()->get();
        $after = $this->getAfterData($user);
        $list['after'] = $after;
        return $this->success($this->auth->id(), $list);
    }

    protected function ChageSelfUserData($user)
    {
        if ($user) {
            if ($user['pid'] > 0) {
                $pid_user = Db::name('user')->where('id', '=', $user['pid'])->fieldRaw('nickname,avatar,name,mobile,set_id,id')->find();
                if($pid_user['set_id']==6){
                    $pid_user['nickname'] =  Db::name('run')->where('user_id', '=', $pid_user['id'])->value('name');
                }
                // $pid_user = User::dbQuery()->where('id', '=', $user['pid'])->fieldRaw('username,avatar,name,mobile,set_id')->find();
                $pid_user['set_name'] = $this->getSetName($pid_user['set_id']);
                $user['pid_user'] = $pid_user;
            }
            //运营中心
            $user['run'] = Db::name('run')->where('id', '=', $user['run_id'])->fieldRaw('name,mobile')->find();

            //售后站
            if ($user['after_sales_user_id'] > 0) {
                $user['after_sales_user'] = Db::name('user')->where('id', '=', $user['after_sales_user_id'])->fieldRaw('username,name,mobile')->find();
            }
        }
        return $user;
    }




    /**
     * 获取我的二维码
     * 
     * @return void
     * @Action
     */
    public function get_my_qr()
    {
        // $qr = new \addons\qrcode\controller\Index;
        // if (empty($this->auth->qr)) {
        //     // if (1) {
        //     $code = $this->EnCode($this->auth->id());
        //     $qr = $qr->get_qr(json_encode(['user_invite_code' => $code]));
        //     Db::name('user')->where('id', '=',$this->auth->id())->update(['qr' => $qr, 'invite_code' => $code]);
        //     $this->auth->qr = $qr;
        //     // $this->auth->save();
        // } else {
        //     $code = $this->auth->invite_code;
        // }
        $user = $this->auth->getUserinfo();
        if (empty($user['qr']))
            $this->UpdateUserInviteCode($this->auth->id());
        return $this->success($user['invite_code'], $user['qr']);
    }

    // /**
    //  * 获取首页app
    //  *
    //  * @return void
    //  * @Action
    // */
    // public function get_index_app()
    // {
    //     $list = Db::name('app')->where('switch','=', 1)->orderRaw('weigh desc')->select()->getArray();
    //     if ($this->auth->isLogin()) {
    //         //如果登陆就按点击率排序
    //         $app_ids = Db::name('appclick')->where('uid','=', $this->auth->id())->orderRaw('num desc')->column('app_id');
    //         if ($app_ids) {
    //             $new = [];
    //             $temp = [];
    //             $end = [];
    //             foreach ($app_ids as $key => $app_id) {
    //                 foreach ($list as $key => $val) {
    //                     if ($val['id'] == $app_id) {

    //                         if (!in_array($val['id'], $temp)) {
    //                             $temp[] = $val['id'];
    //                             $new[] = $val;
    //                         }
    //                         // halt($temp);

    //                     }
    //                 }
    //             }

    //             foreach ($list as $key => $val) {
    //                 if (!in_array($val['id'], $temp)) {
    //                     $temp[] = $val['id'];
    //                     $end[] = $val;
    //                 }
    //             }



    //             if (isset($end)) {
    //                 // var_dump($new,$end);
    //                 $list = array_merge($new, $end);
    //             } else {
    //                 $list = $new;
    //             }

    //             // foreach ($list as $key => $value) {
    //             //     # code...
    //             // }
    //         }
    //     }
    //     return $this->success('ok', $list);
    // }

    // /**
    //  * 点击APP
    //  *
    //  * @param int $id APPid
    //  * @return void
    //  * @Action
    // */
    // public function appclick($id)
    // {
    //     $data['uid'] = $this->auth->id();
    //     $data['app_id'] = $id;
    //     $res = Db::name('appclick')->whereEx($data)->select()->get();
    //     if ($res) {
    //         Db::name('appclick')->whereEx($data)->setInc('num');
    //     } else {
    //         $data['num'] = 1;
    //         Db::name('appclick')->insert($data);
    //     }
    //     return $this->success('ok');
    // }

    // /**
    //  * 修改自动播放
    //  *
    //  * @param int $auto_play_status 自动播放:1=关闭,2=自动
    //  * @return void
    //  */
    // public function update_auto_play_status($auto_play_status = '1')
    // {

    //     // if ($uid == $this->auth->id()) {
    //     //     return $this->error('自己不能邀请自己');
    //     // }
    //     $res = Db::name('user')->where('id', $this->auth->id())->update(['auto_play_status' => $auto_play_status]);
    //     if ($res) {
    //         return $this->success('修改成功', $auto_play_status);
    //     } else {
    //         return $this->error('修改失败', $auto_play_status);
    //     }
    // }



    /**
     * 修改上级
     *
     * @param int $uid 修改上级
     * @param int $role 二维码角色状态1=货主,2=司机
     * @param int $role_status 当前角色状态1=货主,2=司机
     * @return void
     * @Action
     */
    public function update_pid($uid, $role = '2', $role_status = '1')
    {

        if ($uid == $this->auth->id()) {
            return $this->error('自己不能邀请自己');
        }

        $data['role_status'] = $role_status;
        $data['pid'] = $uid;
        $data['uid'] = $this->auth->id();
        $res = Db::name('pid')->whereEx($data)->select()->get();
        if (!$res) {
            $data['time'] = time();
            // Db::name('pid')->insert($data);

            switch ($role_status) {
                case '1':
                    // if($this->auth->pid>0){
                    //     return $this->error('修改失败');
                    // }else{
                    Db::name('user')->where('id', '=', $this->auth->id())->update('pid', $uid);

                    // return $this->success('修改成功');
                    // }
                    break;
                    // case '2':

                    //     // if($this->auth->j_pid>0){
                    //     //     return $this->error('修改失败');
                    //     // }else{
                    //     Db::name('user')->where('id', $this->auth->id())->update('j_pid', $uid);
                    //     // return $this->success('修改成功');
                    //     // }
                    //     break;
                default:
                    return $this->error('没有该类型');
                    break;
            }

            if ($role == '1') {
                //给该货主添加抵扣金
                // $GiftMoney = new \app\api\controller\GiftMoney;
                $GiftMoney->s_invite_success($uid, $this->auth->id());
            }
            return $this->success('修改成功');
        }
    }

    /**
     * 获取用户的粉丝关注评论等信息
     *
     * @param int $uid 用户id
     * @return void
     * @Action
     */
    public function get_user_data($uid = null)
    {
        $uid ?? $this->error('请传递用户id');
        $data = $this->GetUserFansData1($uid);

        return $this->success('ok', $data);
    }

    /**
     * 获取我的已分享成功用户列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     * @Action
     */
    public function get_my_share_list($page = 1, $limit = 10)
    {

        $list = Db::name('user')->where('pid', '=', $this->auth->id())->page($page, $limit)->fieldRaw('id,nickname,money,mobile,pid,avatar,jointime')->select()->getArray();
        $count =  Db::name('user')->where('pid', '=', $this->auth->id())->count();

        // $j_count =  Db::name('user')->where('j_pid', $this->auth->id())->count();
        foreach ($list as $key => &$val) {
            // $val['sum_money'] = Db::name('user_money_log')->where('user_id', $val['id'])->sum('money');
            $val['joindate'] = date('Y-m-d H:i:s', $val['jointime']);
        }
        return $this->success('ok', ['list' => $list, 'count' => $count]);
    }
}
